<template>
  <div
    ref="watermarkContainerRef"
    :class="['editor-watermark-container', $attrs.class]"
    :style="styleValue"
    v-bind="filteredAttrs"
  >
    <slot></slot>
  </div>
</template>

<script setup lang="ts">
import {
  inject,
  computed,
  watch,
  onMounted,
  onUnmounted,
  ref,
  nextTick,
  useAttrs,
  type Ref,
} from "vue";
import type { PageOption } from "../../types";
import {
  useWatermark,
  type UseWatermarkOptions,
} from "../../utils/useWatermark";
import type { StyleValue } from "vue";

defineOptions({
  name: "WatermarkContainer",
  inheritAttrs: false,
});

const $attrs = useAttrs();

// 处理 style 类型
const styleValue = computed<StyleValue | undefined>(() => {
  return $attrs.style as StyleValue | undefined;
});

// 过滤掉 class 和 style，因为我们已经单独处理了
const filteredAttrs = computed(() => {
  const { class: _, style: __, ...rest } = $attrs as Record<string, unknown>;
  return rest;
});

// 注入页面配置
const pageOptions = inject<Ref<PageOption>>("page");

// 水印容器引用
const watermarkContainerRef = ref<HTMLElement | null>(null);

// 水印文本
const watermarkText = computed(() => {
  return pageOptions?.value?.watermark?.text || "";
});

// 水印类型
const watermarkType = computed(() => {
  return pageOptions?.value?.watermark?.type || "compact";
});

// 获取水印配置选项
const getWatermarkOptions = (): UseWatermarkOptions | null => {
  const watermark = pageOptions?.value?.watermark;
  if (!watermark || !watermark.text || !watermark.text.trim()) {
    return null;
  }

  // 根据类型设置间距（紧凑型间距更小，宽松型间距更大）
  const gapX = watermarkType.value === "compact" ? 40 : 80;
  const gapY = watermarkType.value === "compact" ? 40 : 80;

  // 字体配置
  const fontSize = watermark.fontSize || 16;
  const fontFamily = watermark.fontFamily || "SimSun";
  const fontWeight = watermark.fontWeight || "normal";
  const alpha = 0.4; // 设置透明度为 0.8

  // 将 fontColor 转换为 rgba 格式以应用透明度
  let fontColor = watermark.fontColor || "#000000";

  // 如果 fontColor 是 hex 格式，转换为 rgba
  if (fontColor.startsWith("#")) {
    const hex = fontColor.replace("#", "");
    let r: number, g: number, b: number;
    if (hex.length === 3) {
      // #RGB -> #RRGGBB
      r = parseInt(hex[0] + hex[0], 16);
      g = parseInt(hex[1] + hex[1], 16);
      b = parseInt(hex[2] + hex[2], 16);
    } else if (hex.length === 6) {
      // #RRGGBB
      r = parseInt(hex.substring(0, 2), 16);
      g = parseInt(hex.substring(2, 4), 16);
      b = parseInt(hex.substring(4, 6), 16);
    } else {
      // #RRGGBBAA - 忽略 alpha 通道，使用配置的 alpha
      r = parseInt(hex.substring(0, 2), 16);
      g = parseInt(hex.substring(2, 4), 16);
      b = parseInt(hex.substring(4, 6), 16);
    }
    fontColor = `rgba(${r}, ${g}, ${b}, ${alpha})`;
  } else if (fontColor.startsWith("rgb") && !fontColor.includes("rgba")) {
    // 如果是 rgb 格式，转换为 rgba
    fontColor = fontColor.replace("rgb", "rgba").replace(")", `, ${alpha})`);
  } else if (fontColor.startsWith("rgba")) {
    // 如果已经是 rgba，替换 alpha 值
    const rgbaMatch = fontColor.match(
      /rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*[\d.]+)?\)/
    );
    if (rgbaMatch) {
      fontColor = `rgba(${rgbaMatch[1]}, ${rgbaMatch[2]}, ${rgbaMatch[3]}, ${alpha})`;
    }
  }

  // 计算文本尺寸（使用临时canvas测量）
  const canvas = document.createElement("canvas");
  const ctx = canvas.getContext("2d");
  let textWidth = 200; // 默认宽度
  let textHeight = fontSize * 1.5; // 默认高度（行高）

  if (ctx) {
    // 使用与绘制时相同的字体设置
    ctx.font = `${fontWeight} ${fontSize}px ${fontFamily}`;
    const metrics = ctx.measureText(watermark.text);
    textWidth = metrics.width;
    // 使用实际测量到的文本宽度和高度
    // measureText 只提供宽度，高度需要根据字体大小估算
    textHeight = fontSize * 1.2; // 行高，考虑字体实际高度
    // 添加一些额外的安全边距，因为 measureText 可能不够精确
    textWidth = textWidth * 1.1; // 增加 10% 的安全边距
  }

  // 考虑旋转角度（-45度），需要更大的画布来容纳旋转后的文本
  // 旋转后的对角线长度 = sqrt(width^2 + height^2)
  const diagonal = Math.sqrt(textWidth * textWidth + textHeight * textHeight);

  // 增加足够的 padding，确保文本不会被裁剪
  // 对于旋转的文本，需要至少对角线长度 + 额外的边距
  const padding = Math.max(fontSize * 2, 40); // 至少 40px 或字体大小的 2 倍
  const width = Math.max(diagonal + padding * 2, textWidth + padding * 2);
  const height = Math.max(diagonal + padding * 2, textHeight + padding * 2);

  // 构建新API格式的选项
  const options: UseWatermarkOptions = {
    width: width,
    height: height,
    gapX: gapX,
    gapY: gapY,
    rotate: -45,
    alpha: alpha, // 使用设置的透明度 0.8
    fontColor: fontColor,
    lineSpace: fontSize * 0.5, // 行间距
    watermarkContent: {
      type: "text",
      text: watermark.text,
      fontSize: fontSize,
      fontFamily: fontFamily,
      fontWeight: fontWeight,
      fontColor: fontColor,
    },
    zIndex: 1,
    position: "absolute",
  };

  return options;
};

// 初始化水印
let watermarkInstance: ReturnType<typeof useWatermark> | null = null;

const initWatermark = async () => {
  await nextTick();

  if (!watermarkContainerRef.value) {
    console.warn("Watermark: watermarkContainerRef is null");
    return;
  }

  const options = getWatermarkOptions();
  if (!options) {
    // 清除水印
    if (watermarkInstance) {
      watermarkInstance.clear();
      watermarkInstance = null;
    }
    return;
  }

  // 创建或更新水印实例
  if (!watermarkInstance) {
    watermarkInstance = useWatermark(watermarkContainerRef.value);
  }

  try {
    watermarkInstance.setWatermark(options);
  } catch (error) {
    console.error("Watermark: Failed to set watermark", error, options);
  }
};

// 监听水印配置变化
watch(
  () => [
    pageOptions?.value?.watermark?.text,
    pageOptions?.value?.watermark?.type,
    pageOptions?.value?.watermark?.fontColor,
    pageOptions?.value?.watermark?.fontSize,
    pageOptions?.value?.watermark?.fontFamily,
    pageOptions?.value?.watermark?.fontWeight,
    pageOptions?.value?.watermark?.alpha,
  ],
  () => {
    initWatermark();
  },
  { deep: true }
);

onMounted(() => {
  initWatermark();
});

onUnmounted(() => {
  if (watermarkInstance) {
    watermarkInstance.clear();
    watermarkInstance = null;
  }
});
</script>

<style scoped lang="scss">
.editor-watermark-container {
  position: relative;
  width: 100%;
  height: 100%;
  min-height: 100%;

  // 当包含 editor-page-content 类时，应用页面内容样式
  &.editor-page-content {
    transform-origin: 0 0;
    box-sizing: border-box;
    display: flex;
    position: relative;
    background: var(--editor-page-background);
    width: var(--editor-page-width);
    min-height: var(--editor-page-height);
    overflow: visible !important;
    flex-direction: column;

    [contenteditable] {
      outline: none;
    }
  }
}
</style>
